<template>
  <view class="m-page-swiper">
    <x-navigation-bar
      title="新物种"
      desc="发现不一样的好物"
      align="left"
      background="#000"
      color="#fff"
      icon-color="#fff"
    />
    <swiper
      v-if="list"
      :current="current"
      next-margin="80px"
      vertical
      class="m-swiper-vertical"
      @change="handleChange"
    >
      <swiper-item v-for="(item, index) in list" :key="item.pageId" :item-id="item.pageId" class="item">
        <p-product
          :detail="item"
          :index="index"
          :is-active="currentPageId === item.pageId"
          @confirm="handleShowOrderInfo"
        />
      </swiper-item>
    </swiper>

    <view v-if="isEmpty" class="empty">没有更多内容啦</view>

    <!--动画引导-->
    <view v-if="pageTouchGuide" class="m-touch-guide" @touchend="handleClickGuide">
      <view class="pic">
        <x-image src="/assets/images/pic-swiper-touch.gif" />
      </view>
      <text>上滑查看更多好物</text>
    </view>

    <page-container :show="visible" round @afterleave="visible = false">
      <view class="x-order-info">
        <view class="_header">
          <view class="_title">填写订单</view>
          <view class="_cancel" @click.stop="visible = false">
            <x-icon name="icon-025" size="28" color="#C8C9CC" />
          </view>
        </view>
        <p-order-info
          v-if="visible"
          ref="orderInfo"
          is-drawer
          :query="orderQuery"
          :detail="productInfo"
          :page-id="currentPage.pageId"
          :product-id="currentPage.productId"
          :store-info="storeInfo"
        />
      </view>
    </page-container>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import XNavigationBar from '@/components/x-navigation-bar';
import XImage from '@/components/x-image';
import XIcon from '@/components/x-icon';
import POrderInfo from '@/pages/advertising/components/p-order-info';
import PProduct from './components/p-product';

export default {
  name: 'Swiper',
  components: {
    XNavigationBar,
    XImage,
    XIcon,
    PProduct,
    POrderInfo
  },
  props: {},
  data() {
    return {
      query: {},
      orderQuery: {
        sourcePageId: null,
        source: 1028
      },
      isEmpty: false,
      visible: false,
      current: 0,
      currentPageId: 0,
      list: null,
      guideTime: null,
      // 动画引导
      pageTouchGuide: false,
      // 分页相关
      pagination: {
        more: true,
        loading: false,
        pageNum: 1,
        pageSize: 5
      },
      storeDetail: {}
    };
  },
  computed: {
    ...mapState({
      // 商品信息
      productInfo: state => state['product'].productDetail,
      pageQuery: state => state['pages'].pageQuery
    }),
    // 当前页面
    currentPage() {
      return this.list?.find(item => item.pageId === this.currentPageId);
    },
    storeInfo() {
      const { storeId, storeName, companyName, companyAddress, channelCompanyName } = this.storeDetail || {};
      return {
        storeId,
        storeName,
        companyName: companyName,
        companyAddress: companyAddress,
        channelCompanyName: channelCompanyName
      };
    },
    adParams() {
      const { gdt_vid, qq_ac_id, qq_ag_id, clickid, adid, acode, callback, aid, cid, ksUnitId, ksSiteAccountId } = this.pageQuery || {};
      return {
        gdt_vid,
        qq_ac_id,
        qq_ag_id,
        clickid,
        adid,
        acode,
        callback,
        aid,
        cid,
        ksUnitId,
        ksSiteAccountId
      };
    }
  },
  watch: {},
  onLoad(query) {
    this.query = query;
    // 好物推荐增加上广告id，方便数据归因
    const { gdt_vid } = this.pageQuery || {};
    Object.assign(this.orderQuery, {
      gdt_vid,
      sourcePageId: query.pageId,
      ...this.adParams
    });
    this.getList();

    // 滑动提醒
    this.pageTouchGuide = !uni.getStorageSync('SWIPER-TOUCH-GUIDE');
    this.guideTime = setTimeout(() => {
      this.handleClickGuide();
    }, 3000);
  },
  onShow() {
    // 再次返回页面的时候，更新缓存中的数据
    this.$XTrack('onLoad', this.query);
    this.$store.dispatch('pages/setData', {
      previousStatus: this.query.previousStatus || 5
    });
  },
  destroyed() {
    if (this.guideTime) {
      clearInterval(this.guideTime);
    }
  },
  methods: {
    getList() {
      const { loading, more, pageNum, pageSize } = this.pagination;
      if (loading || !more) return false;
      this.pagination.loading = true;
      const params = {
        pageId: this.query.pageId,
        pageNum,
        pageSize
      };
      this.$http({
        url: '/product/page/goods/recommend',
        data: params
      }).then(res => {
        const { gdt_vid } = this.pageQuery || {};
        const data = res.data || [];
        const list = data.map(item => {
          return {
            ...item,
            gdt_vid,
            isPrimaryPage: this.query.primaryPageId === item.pageId,
            sourcePageId: this.query.pageId,
            source: 1028,
            ...this.adParams
          };
        });
        if (pageNum === 1) {
          this.$XTrack('getGoodsRecommend', {
            pageNum,
            count: this.list?.length
          });
          if (list.length) {
            this.list = list;
            // 初始化
            this.currentPageId = this.list[0].pageId;
            this.getPageDetail();
          } else {
            // 无数据时返回上一级页面
            console.log('返回上一级页面');
            uni.navigateBack({
              delta: 1
            });
          }
        } else {
          this.list.push(...list);
        }
        this.isEmpty = true;
        Object.assign(this.pagination, {
          loading: false,
          more: !!data.length,
          pageNum: pageNum + 1
        });
      });
    },
    handleChange(event) {
      const { detail } = event;
      this.current = detail.current;
      this.currentPageId = detail.currentItemId;
      this.getPageDetail();
      if (this.pagination.more && this.current >= this.list.length - 3) {
        this.getList();
      }
    },
    getCurrentPath() {
      const currPath = ['/pages/swiper/index'];
      const query = this.query;
      // 订阅消息场景获取
      const params = this.$tools.object2param(query);
      if (params) currPath.push(params);
      return currPath.join('?');
    },
    getPageDetail() {
      const { pageId, productId, storeId, source } = this.currentPage || {};
      if (pageId) {
        // 投放页详情
        this.$store.dispatch('product/getPageDetail', {
          pageId,
          source,
          pageUrl: this.getCurrentPath()
        }).then((res) => {
          if (res.pageDetail && res.pageDetail.pageStatus === 1) {
            // 只加载已上架的数据
            // 商品详情
            this.$store.dispatch('product/getProductDetail', {
              pageId,
              productId,
              source
            });
            // 可领取的优惠券
            this.$store.dispatch('product/getCouponSendList', {
              storeId,
              productId,
              pageId,
              source: 1
            });
            // 可使用的优惠券
            this.$store.dispatch('product/getCouponList', {
              storeId,
              productId,
              query: {
                pageId,
                source
              }
            });
          } else {
            this.handleError();
          }
        }).catch(() => {
          this.handleError();
        });
      }
    },
    // 显示确认订单表单
    handleShowOrderInfo(detail) {
      this.$http({
        login: true,
        url: '/account/store/base/info',
        method: 'get',
        data: {
          storeId: detail.storeId,
          pageId: detail.pageId
        }
      }).then(res => {
        this.storeDetail = res.data;
      });
      this.orderQuery.isPrimaryPage = detail.isPrimaryPage;
      this.visible = true;
      // 呼起确认订单弹窗
      this.$XTrack('swiperShowPageOrderInfo');
    },
    // 确认引导
    handleClickGuide() {
      uni.setStorageSync('SWIPER-TOUCH-GUIDE', true);
      this.pageTouchGuide = false;
      if (this.guideTime) {
        clearTimeout(this.guideTime);
      }
    },
    // 处理页面异常逻辑
    handleError() {},
  }
};
</script>

<style lang="scss">
.m-page-swiper{
  display: flex; flex-direction: column; height: 100vh; background-color: #000;
  .m-swiper-vertical{
    flex: 1; position: relative; z-index: 2;
    .item{ height: 100%;}
  }
  .empty{ position: absolute; width: 100%; left: 0; bottom: 0; height: 160px; font-size: 28px; display: flex; align-items: center; justify-content: center; text-align: center; color: #707070; z-index: 1;}
  .x-order-info{
    height: 80vh; overflow-y: auto;
    ._header {
      padding: 36px 40px; position: relative;
      ._title { font-size: 32px; color: #323233; text-align: center;}
      ._cancel { width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; position: absolute; right: 0; top: 50%; transform: translate3d(0, -50%, 0);}
    }
  }

  .m-touch-guide{
    width: 100%; height: 100%; position: absolute; display: flex; justify-content: center; align-items: center; flex-direction: column; left: 0; top: 0; z-index: 10000; background-color: rgba(0, 0, 0, 0.4);
    .pic{ width: 550px; height: 550px;}
    text{ font-size: 36px; color: #fff; padding-top: 20px;}
  }
}
</style>
